package com.linran.wxpublic.controller;

import com.linran.wxpublic.domain.json.MsgTemplate;
import com.linran.wxpublic.domain.xml.WeChatArticle;
import com.linran.wxpublic.domain.xml.WeChatImage;
import com.linran.wxpublic.domain.xml.WeChatRequest;
import com.linran.wxpublic.domain.xml.WeChatResponse;
import com.linran.wxpublic.util.JSON;
import com.linran.wxpublic.util.WxUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lin
 * @date 2020-08-17 13:44
 * <p>
 */
@Slf4j
@RequestMapping("wechat")
@RestController
public class WeChatV1Controller {
    public static final String toUser = "touser_openId";
    @Autowired
    private WxUtil wxUtil;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 接口配置信息点击提交之后的验证接口
     *
     * @param param
     * @return
     */
    @GetMapping("/test")
    public String weChatInterFace(GetParameter param) {
        log.info("[weChartParameter] {}", param.toString());
        if (wxUtil.checkSignature(param.getSignature(), param.getTimestamp(), param.getNonce())) {
            log.info("--------验证微信服务号流程结束---------");
        } else {
            log.warn("非微信服务号请求!");
        }
        return param.getEchostr();
    }

    /**
     * 测试token调用接口，获取微信服务ip地址
     *
     * @return
     */
    @GetMapping("/wx_server/list")
    public String listWxServerIp() {
        String wxToken = wxUtil.getWxToken();
        String serverUrl = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=%s";
        return restTemplate.getForObject(String.format(serverUrl, wxToken), String.class);
    }

    /**
     * 消息接收测试并被动回复
     * 被动回复消息时需要加解密
     */
    @PostMapping(value = "/test", consumes = MediaType.TEXT_XML_VALUE, produces = MediaType.TEXT_XML_VALUE)
    public Object normalText(@RequestBody WeChatRequest weChatRequest) {
        System.out.println(JSON.toJSONString(weChatRequest));
//        WeChatResponse weChatResponse = imageResponse(weChatRequest);
//        WeChatResponse weChatResponse = textResponse(weChatRequest, "测试2020");
        WeChatResponse weChatResponse = newsResponse(weChatRequest);
        return weChatResponse;
    }

    private static WeChatResponse newsResponse(WeChatRequest weChatRequest) {
        //图文
        WeChatResponse weChatResponse = new WeChatResponse();
        weChatResponse.setToUserName(weChatRequest.getFromUserName());
        weChatResponse.setFromUserName(weChatRequest.getToUserName());
        weChatResponse.setCreateTime(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));
        weChatResponse.setArticleCount(1);
        weChatResponse.setMsgType("news");
        WeChatArticle article = new WeChatArticle();
        article.setDescription("QQ音乐是腾讯公司推出的一款网络音乐服务产品，海量音乐在线试听、新歌热歌在线首发、歌词翻译、手机铃声下载、高品质无损音乐试听、海量无损曲库、正版 ...");
        article.setTitle("QQ音乐~");
        article.setUrl("https://y.qq.com/");
        article.setPicUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1597848812240&di=04b183ee59358485a0f2fedbcae43f7b&imgtype=0&src=http%3A%2F%2Fe.hiphotos.baidu.com%2Fzhidao%2Fpic%2Fitem%2Fcdbf6c81800a19d8f8ffd40030fa828ba61e4632.jpg");
        List<WeChatArticle> articles = new ArrayList<>();
        articles.add(article);
        weChatResponse.setArticle(articles);
        return weChatResponse;
    }

    private WeChatResponse textResponse(WeChatRequest weChatRequest, String content) {
        //文件回复
        WeChatResponse weChatResponse = new WeChatResponse();
        weChatResponse.setToUserName(weChatRequest.getFromUserName());
        weChatResponse.setFromUserName(weChatRequest.getToUserName());
        weChatResponse.setContent(content);
        weChatResponse.setCreateTime(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));
        weChatResponse.setMsgType("text");
        return weChatResponse;
    }

    private WeChatResponse imageResponse(WeChatRequest weChatRequest) {
        //图片提前上传到素材管理中心
        WeChatResponse weChatResponse = new WeChatResponse();
        weChatResponse.setToUserName(weChatRequest.getFromUserName());
        weChatResponse.setFromUserName(weChatRequest.getToUserName());
        weChatResponse.setCreateTime(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));
        weChatResponse.setMsgType("image");
        WeChatImage weChatImage = new WeChatImage();
        weChatImage.setMediaId("CArgYXr3onHg8n7NnqZxdQPkD2JLKOUGtqbXCgPsQhlv-PSQsoFhmLv_uB85c8qn");
        weChatResponse.setWeChatImage(weChatImage);
        return weChatResponse;
    }

    /*添加客服*/
    @GetMapping("/add/customer_service")
    public ResponseEntity<?> addCustomerService() {
        String wxToken = wxUtil.getWxToken();
        String serverUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));
        String body = "{\n" +
                "     \"kf_account\" : \"test1@test\",\n" +
                "     \"nickname\" : \"客服1\",\n" +
                "     \"password\" : \"pswmd5\"\n" +
                "}";
        HttpEntity<String> httpEntity = new HttpEntity<>(body, headers);
        return restTemplate.postForEntity(String.format(serverUrl, wxToken), httpEntity, String.class);
    }

    @GetMapping(value = "/template/msg")
    public ResponseEntity<?> msgTemplateSend() {
        String wxToken = wxUtil.getWxToken();
        String serverUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";
        MsgTemplate msgTemplate = new MsgTemplate();
        msgTemplate.setTouser(toUser);
        msgTemplate.setUrl("https://www.baidu.com");
        msgTemplate.setTemplateId("BQKwzH1Dn4fVhcQRr6H-VDQOTHGgegMxsDSpUidDD2g");
        msgTemplate.addParam("result", "恭喜你", "#173177");
        msgTemplate.addParam("withdrawMoney", "300w", "#173177");
        msgTemplate.addParam("cardInfo", "900960956461", "#173177");
        msgTemplate.addParam("arrivedTime", "2020-80-80", "#173177");
        msgTemplate.addParam("remark", "测试消息1010", "#173177");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));
        String body = JSON.toJSONString(msgTemplate);
        HttpEntity<String> httpEntity = new HttpEntity<>(body, headers);

        System.out.println("body====>>>>>:" + body);

        return restTemplate.postForEntity(String.format(serverUrl, wxToken), httpEntity, String.class);
    }
}

@ToString
@Getter
@Setter
class GetParameter {
    /**
     * 微信加密签名
     */
    private String signature;
    /**
     * 时间戳
     */
    private String timestamp;
    /**
     * 随机数
     */
    private String nonce;
    /**
     * 随机字符串
     */
    private String echostr;
}